<?php
/**
 * backend公用控制器
 * 所有backend目录下的控制器都需要继承此基类
 * @author: yanxs <541139655@qq.com>
 * @version: 1.0
 * @date: 2021/3/10
 */

namespace App\Http\Controllers\Backend;

use App\Repositories\PrtAuthRuleRepository;
use App\Repositories\PrtAdminRepository;
use App\Repositories\PrtAuthGroupRepository;
use App\Services\Rbac\Menu;
use Illuminate\Http\Request;
use Route;

class BaseController extends \App\Http\Controllers\BaseController
{
    protected $tableTpl = '_table';       //通用列表名称
    protected $form     =  '_form';       //通用form表单名称
    protected $tipSuccessTpl = 'component.tipsSuccess';
    protected $tipWarnTpl  = 'component.tipsWarn';
    protected $noNeedRight = [];    //不需要检查权限的方法名
    protected $codePrefix = '';    //编码前缀
    protected $viewPath = '';      //视图目录地址
    public function __construct()
    {
        $this->checkAuth();
        view()->share("code_prefix",$this->codePrefix);
        view()->share("public_status",$this->buildSelectData(config("status.open_close")));
        view()->share("public_check_status",$this->buildSelectData(config("status.check_status")));
        view()->share("sys_setting",$this->getSysSetting());
        view()->share("static_ver",config("common.static_ver"));
        parent::__construct();
    }
    /**
     * 获取当前用户的信息
     */
    protected function getUserInfo()
    {
       // var_dump(session('admin'));exit;
        $admin = session('admin') ?? [];
        return $admin;
    }
    /**
     * 获取菜单服务类
     * @return object
     */
    protected function menuServices()
    {
        $repoRule = app(PrtAuthRuleRepository::class);
        $repoUser = app(PrtAdminRepository::class);
        $repoRole = app(PrtAuthGroupRepository::class);
        return new Menu($repoUser,$repoRole,$repoRule);
    }

    /**
     *权限检查
     */
    protected function checkAuth()
    {
        //权限控制
        $currentUrl  = \Request::getRequestUri();  //当前路由
        //先确认这个路由是否存在,这种很高频的清求可以使用缓存策图,路由+用户id为键，记录为值.
        if (strpos($currentUrl,"?")) {
            $currentUrl = substr($currentUrl,0,strpos($currentUrl,"?"));
        }

        $info = app(PrtAuthRuleRepository::class)->getRow(['rule_route' => trim($currentUrl, "/")]);
        //目的是为了解决 xxxx/xxxx/{xxx}这种路由权限分配的问题，这里我只做一级参数处理，多级的自行处理

        if (empty($info)) {
            $arrUlr = explode("/",$currentUrl);
            array_pop($arrUlr);
            $currentUrl = implode("/",$arrUlr);
        } else {
            view()->share("menu_remark",isset($info['rule_remark']) ? $info['rule_remark'] : $info['rule_name']);
        }
        $noNeedRight = config('common.no_need_right'); //无需验证的路由
        if (!in_array($currentUrl, $noNeedRight)) {
            $menuService = $this->menuServices();  //子类必须有这个方法
            $userInfo = $this->getUserInfo();
            if (empty($userInfo)) {
                if (\Request::ajax() && !in_array('*',$this->noNeedRight)) {
                    echo json_encode(['status' => 404, 'success' => 'false', 'message' =>"登录已过期，请重新登录",'err_msg' =>"登录已过期，请重新登录"]);exit;
                    exit;
                } else {
                    return redirect("/login?return_url=".$currentUrl);
                }
            }
            //路由检查
            $isAuth = $menuService->mathUrl($currentUrl,$this->noNeedRight,$userInfo['group_id']??0);
            if (!$isAuth) {
                if (\Request::ajax()) {
                     echo json_encode(['status' => 404, 'success' => 'false', 'message' =>"无此操作权限",'err_msg' =>"无此操作权限"]);exit;
                    // $this->jsonFailed("无权访问");exit;
                } else {
                    echo "无权操作及访问！";exit;
                }
            }
        }
        return true;
    }
    /**
     * 组成下拉框选项
     * @param $data
     * @return string[]
     */
    protected function buildSelectData($data)
    {

        return [''=>'--请选择--'] + $data;
    }
}
